package com.iretailer.report.quartz.horizon;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iretailer.report.quartz.horizon.common.ClientHttpMethod;
import com.iretailer.report.quartz.horizon.common.CreatRestTemplate;
import com.iretailer.report.quartz.horizon.common.Signer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Auther: xjw
 * @Date: 2019/10/15 0015 17:26
 * @Description:
 */
public class DeviceSampleCode {
    private final static Logger log = LoggerFactory.getLogger(DeviceSampleCode.class);

    public static void main(String[] args) {
        Signer signer = new Signer(Settings.AK, Settings.SK);

        // 获取设备空间接口 GET接口示例
//        getDeviceSpacesSample(signer);

        // 查询设备列表
        getDevices(signer);

        // 查询设备 信息
//        getDeviceMessage(signer);
    }

    /**
     * 获取设备空间接口 GET接口示例
     */
    public static void getDeviceSpacesSample(Signer signer) {
        String API_DEVICE_SPACES_LIST = "/openapi/v1/device_spaces";
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        params.put("current", "1");
        params.put("per_page", "10");
        ResponseEntity<String> result = null;
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, API_DEVICE_SPACES_LIST, headers, params);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建设备空间
     *
     * @param signer
     */
    public static void createDeviceSpaceSample(Signer signer) {
        String APIURL = "/openapi/v1/device_spaces";
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put("content-type", "application/json");
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        ResponseEntity<String> result = null;
        try {
            JSONObject body = new JSONObject();
            body.put("name", "space_smple");
            body.put("description", "description");
            body.put("extra", "extra");
//            String body = "{\"name\":\"space_smple\",\"description\":\"your description\",\"extra\":\"your extra\"}";
            result = ClientHttpMethod.getHttpMethod(signer).httpPOST(String.class, APIURL, headers, params, JSON.toJSONString(body));
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 更新设备空间 PUT接口示例
     *
     * @param signer
     * @return
     */
    public static String updateDeviceSpaceSample(Signer signer, String spaceID) {
        String API_CREATE_DEVICESPACE = "/openapi/v1/device_spaces/" + spaceID;
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put(URLEncoder.encode("content-type"), URLEncoder.encode("application/json"));
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        try {
            String authorization = signer.Sign(HttpMethod.PUT, API_CREATE_DEVICESPACE, params, headers);
            String path = "http://" + headers.get(Settings.HOST) + API_CREATE_DEVICESPACE;
            URL url = new URL(path); // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // connection.setRequestProperty("设置请求头key", "请求头value");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod(RequestParam.HTTP_METHOD_PUT);
            connection.setRequestProperty("authorization", authorization);
            connection.setRequestProperty(URLEncoder.encode("content-type"), URLEncoder.encode("application/json"));
            connection.setRequestProperty(Settings.HOST, Settings.PAAS_HOST);
            connection.connect();
            // 修改为自己要创建的设备空间信息
            String body = "{\"name\":\"your name\",\"description\":\"your description\",\"extra\":\"your extra\"}";
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求失败!");
            return "error";
        }
    }


    /**
     * 删除设备空间 DELETE接口示例
     *
     * @param signer
     * @return
     */
    public static String deleteDeviceSpaceSample(Signer signer, String spaceID) {
        String API_CREATE_DEVICESPACE = "/openapi/v1/device_spaces/" + spaceID;
        SortedMap<String, String> headers = new TreeMap<String, String>();
        SortedMap<String, String> params = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        try {
            String authorization = signer.Sign(HttpMethod.DELETE, API_CREATE_DEVICESPACE, params,
                    headers);
            String path = "http://" + headers.get(Settings.HOST) + API_CREATE_DEVICESPACE;
            URL url = new URL(path); // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // connection.setRequestProperty("设置请求头key", "请求头value");
            connection.setDoInput(true);
            connection.setRequestMethod(RequestParam.HTTP_METHOD_DELETE);
            connection.setRequestProperty("authorization", authorization);
            connection.setRequestProperty(Settings.HOST, Settings.PAAS_HOST);
            connection.connect();
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求失败!");
            return "error";
        }
    }

    /**
     * 查询设备列表
     *   认证不通过
     * @param signer
     */
    public static void getDevices(Signer signer) {
        String API_Devices = "/openapi/v2/devices";
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
//        headers.put(URLEncoder.encode("content-type"), URLEncoder.encode("application/json"));
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        params.put("current", "1");
        params.put("per_page", "10");
        params.put("space_id", "d104e5125d789e5c5a579004_YiRGEJCF");
        params.put("attributes", "capture_config");
//        params.put("attributes", "RecogApp");
        ResponseEntity<String> result = null;
        try {
            String authorization = signer.Sign(HttpMethod.GET, API_Devices, params, headers);

            String param = Signer.getCanonicalQueryString(params, Signer.DEFAULT_ENCODING);

            URI url = URI.create(String.format("http://%s%s?%s&authorization=%s", headers.get(Settings.HOST), API_Devices, param, authorization));

            result = CreatRestTemplate.getRestTemplate().getForEntity(url, String.class);
//            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, API_Devices, headers, params);

            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 查询设备信息
     *
     * @param signer
     */
    public static void getDeviceMessage(Signer signer) {
        String API_Devices_SN = String.format("/openapi/v2/devices/%s", "0694E001020110625L");
        SortedMap<String, String> params = new TreeMap<String, String>();
        SortedMap<String, String> headers = new TreeMap<String, String>();
        headers.put(Settings.HOST, Settings.PAAS_HOST);
        ResponseEntity<String> result = null;
        try {
            result = ClientHttpMethod.getHttpMethod(signer).httpGet(String.class, API_Devices_SN, headers, params);
            log.error(String.valueOf(result.getStatusCode()));
            log.error(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
